from typing import List, Optional, Dict, Union
import time
from Logs.logs import forge_logger
from requests import request


def build_request_body(mapping: Optional[Dict[str, Dict[str, Optional[str]]]] = None, user_id: Union[str, int] = 412) -> Dict[str, List]:
    """
    构建请求体
    :param user_id: 用户 id
    :param mapping: key为埋点列表中的值，value为这个埋点需要传入的参数
    :return: 埋点的body
    """

    datas = {"datas": []}

    def build_data(key: str, value: Optional[Dict[str, str]] = None) -> str:
        timestamp = int(time.time() * 1000)
        data = f"{key}__{timestamp}__"
        if value:
            data += "&&".join([f"{k}::{v}" for k, v in value.items()])
        if str(data).endswith("__"):
            data += f"user_id::{user_id}&&ut::1"
        else:
            data += f"&&user_id::{user_id}&&ut::1"
        forge_logger.success(f"埋点的key:{key},传入的参数{value},拼接后为:{data}")
        return data

    if mapping:
        for key, value in mapping.items():
            data = build_data(key, value)
            datas["datas"].append(data)
    forge_logger.info(f"请求体为:{datas}")
    return datas


def build_request_query(**kwargs) -> dict:
    """
    构建请求查询参数
    :param kwargs: 任意值添加到字典
    :return: 查询参数字典
    """
    query_dic = {
        'biz': 'suki',
        'appv': '2.8.8',
        'appc': '20800800',
        'sw': '1220',
        'sh': '2712',
        'imei': '',
        'aid': 'f4fb87bf2af1d58d',
        'oaid': 'b9947d0a2e86a31e',
        'vaid': 'fce1e24b085c897b',
        'aaid': '0f0a3004-4e0b-453c-a40d-2aaeab486719',
        'mac': '',
        'imsi': '1',
        'oper': '46002',
        'from': 'xiaomi',
        'brand': 'Redmi',
        'model': '2312DRA50C',
        'deviceid': 'b9947d0a2e86a31e',
        'os': 'android',
        'osv': '34',
        'region': 'CN'
    }
    for key, value in kwargs.items():
        query_dic[key] = value
    forge_logger.info(f"请求查询参数为:{query_dic}")
    return query_dic


def send_request(data: Dict[str, List], query: Optional[Dict[str, str]] = None) -> dict:
    """
    对埋点接口发送请求
    :param data: body参数
    :param query: 查询参数
    :return: 埋点接口返回的json
    """
    if query is None:
        query = build_request_query()
    pock_url = "https://test.codeffect.top/statistic/poke"
    response = request("POST", pock_url, json=data, params=query).json()
    forge_logger.debug(f"请求的url:{pock_url}请求参数为:{data},查询参数为:{query}")
    forge_logger.success(f"请求响应为:{response}")
    return response


if __name__ == '__main__':
    data = build_request_body(
        {"GuideSuki.CJ.IM.2": None, "MaterialDownload.SUC": {"type": "other", "test": "212323"}})
    query = build_request_query(biz='mua')
    send_request(data, query)
